package com.zhenwei.zscm.repo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhenwei.zscm.common.utils.Linq;
import com.zhenwei.zscm.entity.OrderExportEntity;
import com.zhenwei.zscm.mapper.IOrderExportMapper;
import com.zhenwei.zscm.mappings.OrderExportMapping;
import com.zhenwei.zscm.model.dto.order.OrderExportDTO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrderExportRepo extends ServiceImpl<IOrderExportMapper, OrderExportEntity> {

    public List<OrderExportDTO> getAll(List<String> orderIds) {
        if (orderIds == null || orderIds.isEmpty()) {
            return new ArrayList<>();
        }
        if(orderIds.size() < 2000) {
            var q = new LambdaQueryWrapper<OrderExportEntity>()
                    .in(OrderExportEntity::getGuid, orderIds)
                    .orderByAsc(OrderExportEntity::getOrderNumber)
                    .orderByAsc(OrderExportEntity::getProductSn);
            List<OrderExportEntity> list = this.list(q);
            return Linq.mapList(list, OrderExportMapping.INSTANCE::entity2Dto);
        }
        int batchSize = 2000;
        var list = new ArrayList<OrderExportDTO>();
        var pageNo = 1;
        while (true) {
            List<String> pageOrderIds = Linq.page(orderIds, pageNo, batchSize);
            if(Linq.isEmpty(pageOrderIds)) {
                break;
            }
            var q = new LambdaQueryWrapper<OrderExportEntity>()
                    .in(OrderExportEntity::getGuid, pageOrderIds)
                    .orderByAsc(OrderExportEntity::getOrderNumber)
                    .orderByAsc(OrderExportEntity::getProductSn);
            List<OrderExportEntity> pageList = this.list(q);
            if(Linq.isEmpty(pageList)) {
                continue;
            }
            pageNo++;
            list.addAll(Linq.mapList(pageList, OrderExportMapping.INSTANCE::entity2Dto));
        }
        return list;
    }
}
